﻿using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.ImageEditor;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using XCI.Helper;
using XCI.Windows.Core;
using XCI.Windows.Helper;

namespace XCI.Windows.Forms
{
    public partial class FrmImagePreview : FrmBase
    {
        private List<string> _fileList = new List<string>();
        private string _path;
        private Image _original;
        private Image _current;
        private XCIOverlayForm _overlay = new XCIOverlayForm();

        public FrmImagePreview()
        {
            InitializeComponent();
        }

        public FrmImagePreview(List<string> fileList, string path)
        {
            InitializeComponent();
            _fileList = fileList;
            _path = path;
        }

        public FrmImagePreview(string path)
        {
            InitializeComponent();
            _path = path;
        }

        public FrmImagePreview(Image image)
        {
            InitializeComponent();
            _original = image;
        }

        private void LoadImage()
        {
            if (!string.IsNullOrEmpty(_path) && ImageHelper.IsImage(_path) && File.Exists(_path))
            {
                pictureEdit1.LoadAsync(_path);
            }
            else if (_original != null)
            {
                pictureEdit1.Image = _original;
            }
        }

        private void SetButtonStatus()
        {
            var hasImage = pictureEdit1.Image != null;

            btnPre.Enabled = _fileList.Count > 0 && _fileList.IndexOf(_path) > 0;
            btnNext.Enabled = _fileList.Count > 0 && _fileList.IndexOf(_path) < _fileList.Count - 1;

            btnShrink.Enabled = pictureEdit1.Properties.ZoomPercent > 25 && hasImage;
            btnZoomIn.Enabled = pictureEdit1.Properties.ZoomPercent < 1000 && hasImage;
            btnActual.Enabled = pictureEdit1.Properties.ZoomPercent != 100 && hasImage;

            btnEdit.Enabled = hasImage;
            btnExport.Enabled = hasImage;

            btnRestore.Enabled = _current != null && _original != null;
            btnRotateLeft.Enabled = hasImage;
            btnRotateRight.Enabled = hasImage;

            btnBlackAndWhite.Enabled = hasImage;
            btnInverted.Enabled = hasImage;
            btnRelievo.Enabled = hasImage;
            btnMirror.Enabled = hasImage;
        }

        private void SetZoomPercent(double percent)
        {
            if (pictureEdit1.Properties.SizeMode != PictureSizeMode.Clip)
            {
                pictureEdit1.Properties.SizeMode = PictureSizeMode.Clip;
            }
            pictureEdit1.Properties.ZoomPercent = percent;
        }

        private void SetImage(Func<Image, Image> callback)
        {
            Image old = null;
            if (_current == null)
            {
                _current = _original;
            }
            else
            {
                old = _current;
            }

            _current = callback?.Invoke(_current);
            pictureEdit1.Image = _current;
            if (old != null) old.Dispose();
            SetButtonStatus();
        }

        private void FrmImagePreview_Load(object sender, EventArgs e)
        {
            LoadImage();
            SetButtonStatus();
        }

        private void PictureEdit1_LoadCompleted(object sender, EventArgs e)
        {
            _original = pictureEdit1.Image;
        }

        private void BtnPre_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var index = _fileList.IndexOf(_path);
            _path = _fileList[index - 1];
            LoadImage();
            SetButtonStatus();
        }

        private void BtnNext_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var index = _fileList.IndexOf(_path);
            _path = _fileList[index + 1];
            LoadImage();
            SetButtonStatus();
        }

        private void BtnShrink_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var percent = pictureEdit1.Properties.ZoomPercent - 25;
            SetZoomPercent(percent);
            SetButtonStatus();
        }

        private void BtnZoomIn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var percent = pictureEdit1.Properties.ZoomPercent + 25;
            SetZoomPercent(percent);
            SetButtonStatus();
        }

        private void BtnActual_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetZoomPercent(100);
            SetButtonStatus();
        }


        private void BtnRotate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetImage(p =>
            {
                var img = new Bitmap(p);
                img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                return img;
            });
        }

        private void BtnRotateRight_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetImage(p =>
            {
                var img = new Bitmap(p);
                img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                return img;
            });
        }


        private void BtnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (pictureEdit1.Image == null)
            {
                MessageBoxHelper.ShowWarn("当前没有图片");
                return;
            }
            if (this.saveFile.ShowDialog() == DialogResult.OK)
            {
                FileInfo fileInfo = new FileInfo(this.saveFile.FileName);
                FileStream fileStream = null;
                try
                {
                    if (fileInfo.Exists)
                        fileInfo.Delete();
                    fileStream = new FileStream(this.saveFile.FileName, FileMode.Create);
                    ImageFormat format;
                    switch (this.saveFile.FilterIndex)
                    {
                        case 1:
                            format = ImageFormat.Bmp;
                            break;
                        case 2:
                            format = ImageFormat.Gif;
                            break;
                        case 4:
                            format = ImageFormat.Png;
                            break;
                        default:
                            format = ImageFormat.Jpeg;
                            break;
                    }
                    pictureEdit1.Image.Save(fileStream, format);
                    //MessageBoxHelper.ShowWarn("导出成功");
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                finally
                {
                    fileStream?.Close();
                }
            }
        }

        private void BtnMirror_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetImage(p =>
            {
                var img = new Bitmap(p);
                img.RotateFlip(RotateFlipType.RotateNoneFlipX);
                return img;
            });
        }

        private void BtnRestore_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_current != null)
            {
                _current.Dispose();
                _current = null;
                pictureEdit1.Image = _original;
                SetButtonStatus();
            }
        }

        private void BtnBlackAndWhite_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                btnBlackAndWhite.Enabled = false;
                _overlay.Show(pictureEdit1);
                _overlay.SetText("正在处理...");

                SetImage(p =>
                {
                    return ImageHelper.HeiBai(p);
                });
            }
            finally
            {
                btnBlackAndWhite.Enabled = true;
                _overlay.Close();
                SetButtonStatus();
            }

        }

        private void BtnInverted_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                btnInverted.Enabled = false;
                _overlay.Show(pictureEdit1);
                _overlay.SetText("正在处理...");

                SetImage(p =>
                {
                    return ImageHelper.FanSe(p);
                });
            }
            finally
            {
                btnInverted.Enabled = true;
                _overlay.Close();
                SetButtonStatus();
            }
        }

        private void BtnRelievo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                btnRelievo.Enabled = false;
                _overlay.Show(pictureEdit1);
                _overlay.SetText("正在处理...");

                SetImage(p =>
                {
                    return ImageHelper.FuDiao(p);
                });
            }
            finally
            {
                btnRelievo.Enabled = true;
                _overlay.Close();
                SetButtonStatus();
            }
        }

        private void BtnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (ImageEditorDialog imageEditorDialog = new ImageEditorDialog())
            {
                Image old = null;
                if (_current == null)
                {
                    _current = _original;
                }
                else
                {
                    old = _current;
                }
                var dialogResult = imageEditorDialog.ShowDialog(_current, FindForm());
                if (dialogResult == DialogResult.OK)
                {
                    _current = imageEditorDialog.Image;
                    pictureEdit1.Image = _current;
                    if (old != null) old.Dispose();
                    SetButtonStatus();
                }
            }
        }
    }
}
